package com.vanke.vms.management.dao.daoImpl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Hibernate;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.vanke.vms.common.domain.AddInfo;
import com.vanke.vms.common.domain.Info;
import com.vanke.vms.common.domain.Pair;
import com.vanke.vms.management.dao.ViewInfoDao;

public class ViewInfoDaoImpl extends HibernateDaoSupport implements ViewInfoDao {
	public List<Info> viewInfo(String key, String value) {
		return (List<Info>) getHibernateTemplate().find(
				"from Info as inf where inf." + key + " like '%" + value + "%' order by inf.infoId");
	}

	// 查看用户选择的列，执行select inf.houseSet,inf.houseNum,... from Info ，赋给List<Map>
	// 不用addSchalar就能把createSQLQuery(sql).list()返回的list强制转换成String的list
	public List<Map<String, String>> viewSelectedInfo(
			List<Pair> selectedViewList) {// selectedViewList:Pair<"houseSet",cname,"楼盘">
		String sql = "select inf.infoid,inf.";// +"from Info as inf";
		for (int i = 0; i < selectedViewList.size() - 1; i++) {
			sql = sql + selectedViewList.get(i).getPname() + ",inf.";
		}
		sql = sql
				+ selectedViewList.get(selectedViewList.size() - 1).getPname()
				+ " from vms.info as inf";

		SessionFactory sessionfactory = getHibernateTemplate()
				.getSessionFactory();
		Session session = sessionfactory.openSession();
		SQLQuery queryResult = session.createSQLQuery(sql);
		queryResult = queryResult.addScalar("infoid", Hibernate.INTEGER);
		for (int i = 0; i < selectedViewList.size(); i++) {
			queryResult = queryResult.addScalar(selectedViewList.get(i)
					.getPname(), Hibernate.STRING);
		}
		// test
		List<Object[]> tmpList = queryResult.list();
		session.close();
		List<Map<String, String>> mapList = new ArrayList<Map<String, String>>();
		for (int i = 0; i < tmpList.size(); i++) {
			Object[] o = tmpList.get(i);
			Map<String, String> map = new HashMap<String, String>();
			map.put("infoid", ((Integer) o[0]).toString());
			for (int j = 0; j < selectedViewList.size(); j++) {
				map.put(selectedViewList.get(j).getCname(), (String) o[j + 1]);// Cname是中文，楼盘
			}
			mapList.add(map);
		}

		return mapList;
	}

	public List<Map<String, String>> viewSelectedAddiInfo(
			List<Map<String, String>> infoList, List<String> addiViewList) {
		SessionFactory sessionfactory = getHibernateTemplate()
				.getSessionFactory();
		Session session = sessionfactory.openSession();
		// 获得infoIdList，为了查询高效率，一次把多条信息全部拿回来
		List<Integer> infoidList;// = new ArrayList<Integer>();
		// 这样取infoId是不对的，要从addinfo表中取
		// for (int i = 0; i < infoList.size(); i++) {
		// infoidList.add(Integer.parseInt(infoList.get(i).get("infoid")));
		// }
		if(addiViewList.size() <= 0)
			return infoList;
		String sql = "select distinct infoid from vms.info order by infoid";
		infoidList = (List<Integer>) session.createSQLQuery(sql).addScalar(
				"infoid", Hibernate.INTEGER).list();

		String idlist = "(";
		for (int i = 0; i < infoidList.size() - 1; i++) {
			idlist += infoidList.get(i).toString();
			idlist += ",";
		}
		idlist += infoidList.get(infoidList.size() - 1).toString();
		idlist += ")";

		String cnamelist = "('";
		for (int i = 0; i < addiViewList.size() - 1; i++) {
			cnamelist += addiViewList.get(i).substring(
					addiViewList.get(i).indexOf("@") + 1,
					addiViewList.get(i).length());
			cnamelist += "','";
		}
		// cnamelist += addiViewList.get(addiViewList.size() - 1);
		cnamelist += addiViewList.get(addiViewList.size() - 1).substring(
				addiViewList.get(addiViewList.size() - 1).indexOf("@") + 1,
				addiViewList.get(addiViewList.size() - 1).length());
		cnamelist += "')";// 错误，弄成了Pname@cname

		String hql = "from AddInfo as adi where adi.infoId in " + idlist
				+ " and adi.cname in " + cnamelist + " order by adi.infoId ";
		// String hql = "from AddInfo as adi where adi.infoId in " + idlist
		// + " order by adi.infoId ";
		session.close();
		
		List<AddInfo> addinfolist = (List<AddInfo>) getHibernateTemplate()
				.find(hql);
		
		// 作个中间处理，把所有的AddInfo，建一个Map<Integer,List<AddInfo>>，Integer是infoId，这样效率能高点
		Map<Integer, List<AddInfo>> map = new HashMap<Integer, List<AddInfo>>();
		for (int i = 0; i < infoidList.size(); i++) {
			List<AddInfo> tmplist = new ArrayList<AddInfo>();
			map.put(infoidList.get(i), tmplist);
		}// 创建的Map里边的value(List)都是空的
		// 下边就是把所有的AddInfo都插入到这个Map中
		for (int i = 0; i < addinfolist.size(); i++) {
			Integer ser = addinfolist.get(i).getInfoId();
			List<AddInfo> tmplist = map.get(ser);
			if (tmplist == null) {
				System.out.println("error,no infoid exist\n");
				continue;
			}
			tmplist.add(addinfolist.get(i));
			map.put(ser, tmplist);
		}// 中间处理结束

		if (infoList.size() == 0) {
			
			for(int i=0;i<infoidList.size();i++){
				List<AddInfo> curAddInfoList = map.get(infoidList.get(i));
				Map<String, String> infomap = new HashMap<String,String>();
				infomap.put("infoid", infoidList.get(i).toString());
				for (int j = 0; j < curAddInfoList.size(); j++){
					AddInfo curAddiInfo = curAddInfoList.get(j);
					for (int k = 0; k < addiViewList.size(); k++) {
						// 把Pname@Cname分开
						String curPname = addiViewList.get(k).substring(0,
								addiViewList.get(k).indexOf("@"));
						String curCname = addiViewList.get(k).substring(
								addiViewList.get(k).indexOf("@") + 1,
								addiViewList.get(k).length());
						if (curAddiInfo.getPname().equals(curPname)
								&& curAddiInfo.getCname().equals(curCname)) {
							infomap.put(curPname + ":" + curCname, curAddiInfo
									.getContent());
							break;
						}
					}
				}
				infoList.add(infomap);
			}
		} else {
			for (int i = 0; i < infoList.size(); i++) {
				// 对每个Info,把对应的addInfo都添加到Info的List中
				List<AddInfo> curAddInfoList = map.get(Integer
						.parseInt(infoList.get(i).get("infoid")));
				Map<String, String> infomap = infoList.get(i);
				for (int j = 0; j < curAddInfoList.size(); j++) {
					AddInfo curAddiInfo = curAddInfoList.get(j);
					for (int k = 0; k < addiViewList.size(); k++) {
						// 把Pname@Cname分开
						String curPname = addiViewList.get(k).substring(0,
								addiViewList.get(k).indexOf("@"));
						String curCname = addiViewList.get(k).substring(
								addiViewList.get(k).indexOf("@") + 1,
								addiViewList.get(k).length());
						if (curAddiInfo.getPname().equals(curPname)
								&& curAddiInfo.getCname().equals(curCname)) {
							infomap.put(curPname + ":" + curCname, curAddiInfo
									.getContent());
							break;
						}
					}
				}
				infoList.add(i, infomap);
				infoList.remove(i + 1);
			}
		}

		return infoList;
	}

	//通过所有的idList和所有的addInfo的头信息，返回一个Map<id,与头信息一一对应的值的信息>
	public Map<Integer, List<String>> viewAddInfo(List<Integer> idList, List<Pair> allAddInfoHeadList) {
		
		String allIdList = "(";
		for(int i=0 ; i<idList.size()-1 ; i++){
			allIdList = allIdList + idList.get(i).toString();
			allIdList = allIdList + ",";
		}
		allIdList = allIdList + idList.get(idList.size()-1).toString();
		allIdList = allIdList + ")";
		
		Map<Integer, List<String>> resultMap = new HashMap<Integer, List<String>>();
		for(int i=0;i<idList.size();i++){
			resultMap.put(idList.get(i), new ArrayList<String>());
		}
		
		//对每一个Pname@cname,找到每个InfoId对应的value，并放入这个Map的List中
		for(int i=0;i<allAddInfoHeadList.size();i++){
			String hql = "from AddInfo as adi where adi.pname='"+allAddInfoHeadList.get(i).getPname()+
						"' and adi.cname='"+allAddInfoHeadList.get(i).getCname()+"' and adi.infoId in " +
						allIdList + " order by adi.infoId";
			List<AddInfo> addinfolist = (List<AddInfo>) getHibernateTemplate()
				.find(hql);
			int k = 0;
			int j = 0;
			while(j<idList.size() && k<addinfolist.size()){
				List<String> curStringListInTheMap = resultMap.get(idList.get(j));//从Map中得到InfoId是当前值的List
				if(idList.get(j) == addinfolist.get(k).getInfoId()){
					if(curStringListInTheMap != null)
						curStringListInTheMap.add(addinfolist.get(k).getContent());
					else{
						System.out.println("error!!!!!!!!!!!!!!!!!!");
					}
					k++;
				}
				else{
					if(curStringListInTheMap != null)
						curStringListInTheMap.add("");
					else{
						System.out.println("error!!!!!!!!!!!!!!!!!!");
					}
				}
				resultMap.put(idList.get(j), curStringListInTheMap);//把List更新后写回Map
				j++;
			}
			for(;j<idList.size();j++){
				List<String> curStringListInTheMap = resultMap.get(idList.get(j));
				curStringListInTheMap.add("");
				resultMap.put(idList.get(j), curStringListInTheMap);
			}
		}
		return resultMap;
	}
	
	public List<Integer> getInfoIdListByPCName(String pname, String cname, String viewvalue){
		String sql = "select distinct adi.infoid from vms.addinfo as adi where adi.pname = '" +
				pname + "' and adi.cname = '" + cname +"' and adi.content like '%" +
						viewvalue+ "%' order by adi.infoid";
		SessionFactory sessionfactory = getHibernateTemplate()
			.getSessionFactory();
		Session session = sessionfactory.openSession();
	
		List<Integer> infoIdList = (List<Integer>) session.createSQLQuery(sql).addScalar("infoid", Hibernate.INTEGER).list();
		
		session.close();
		return infoIdList;
	}
	
	public List<Info> getAllInfoByInfoIdList(List<Integer> infoIdList){
		String infoidListString = "(";
		for(int i=0;i<infoIdList.size()-1;i++){
			infoidListString += infoIdList.get(i).toString();
			infoidListString += ",";
		}
		infoidListString += infoIdList.get(infoIdList.size()-1).toString();
		infoidListString += ")";
		String hql = "from Info as inf where inf.infoId in "+infoidListString +" order by inf.infoId";
		
		List<Info> infoList = (List<Info>)getHibernateTemplate().find(hql);
		
		return infoList;
	}

	public List<Pair> assembleList() {
		SessionFactory sessionfactory = getHibernateTemplate()
				.getSessionFactory();
		Session session = sessionfactory.openSession();// sessionfactory.getCurrentSession();//error
		String sql = "select ad.pname,ad.cname from vms.addctrl as ad order by ad.pname";
		// List<Object> list = session.createSQLQuery(sql).list();
		List<Object[]> list = session.createSQLQuery(sql).addScalar("pname",
				Hibernate.STRING).addScalar("cname", Hibernate.STRING).list();
		session.close();
		List<Pair> plist = new ArrayList<Pair>();
		for (int i = 0; i < list.size(); i++) {
			Object[] o = list.get(i);
			Pair tmpPair = new Pair((String) o[0], (String) o[1]);
			plist.add(tmpPair);
		}
		return plist;
	}
}
